package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

	@Autowired
	private CategoryMapper categoryMapper;

	//新增分类
	@Override
	public void add(Category category) {
		//补充属性值
		category.setCreateTime(LocalDateTime.now());
		category.setUpdateTime(LocalDateTime.now());
		//根据ThreadLocalUtil获取当前用户的id
		Map<String, Object> map = ThreadLocalUtil.get();
		Integer userId = (Integer) map.get("id");
		category.setCreateUser(userId);
		//调用mapper中的add方法操作数据库
		categoryMapper.add(category);
	}

	//获取文章分类列表
	@Override
	public List<Category> list() {
		//根据ThreadLocalUtil获取当前用户的id
		Map<String, Object> map = ThreadLocalUtil.get();
		Integer userId = (Integer) map.get("id");

		return categoryMapper.list(userId);
	}

	//获取文章分类详情
	@Override
	public Category findById(Integer id) {
		Category category = categoryMapper.findById(id);
		return category;
	}

	//更新文章分类
	@Override
	public void update(Category category) {
		category.setUpdateTime(LocalDateTime.now());
		categoryMapper.update(category);
	}

	@Override
	public boolean deleteById(Integer id) {
		if(categoryMapper.findById(id)!=null){
			categoryMapper.deleteById(id);
			return true;
		}else{
			return false;
		}
	}
}
